"""
验证相关的Celery任务
"""

import asyncio
from typing import Dict, Any

from celery import current_task
from .celery import celery
from services.verification_service import verification_service
from database import AsyncSessionLocal
from utils.logger import get_logger

logger = get_logger(__name__)


@celery.task(bind=True, max_retries=3)
def verify_sync_result(self, execution_id: int) -> Dict[str, Any]:
    """
    验证同步结果

    Args:
        execution_id: 执行记录ID

    Returns:
        验证结果
    """
    task_id = current_task.request.id

    logger.info(
        "开始验证同步结果",
        execution_id=execution_id,
        task_id=task_id
    )

    try:
        # 运行异步任务
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(
                _verify_sync_result_async(execution_id)
            )
            return result
        finally:
            loop.close()

    except Exception as e:
        logger.error(
            "同步结果验证失败",
            execution_id=execution_id,
            error=str(e)
        )
        raise


async def _verify_sync_result_async(execution_id: int) -> Dict[str, Any]:
    """异步验证同步结果"""
    async with AsyncSessionLocal() as db:
        verification_results = await verification_service.verify_sync_result(
            execution_id=execution_id,
            db=db
        )

        return {
            "execution_id": execution_id,
            "verification_results": verification_results,
            "verified_repos": len(verification_results),
            "success_count": len([r for r in verification_results if r.get("overall_status") == "success"]),
            "failure_count": len([r for r in verification_results if r.get("overall_status") in ["failure", "error"]])
        }


@celery.task
def verify_before_sync(task_id: int) -> Dict[str, Any]:
    """
    同步前验证

    Args:
        task_id: 任务ID

    Returns:
        验证结果
    """
    logger.info("开始同步前验证", task_id=task_id)

    try:
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        try:
            result = loop.run_until_complete(
                verification_service.verify_before_sync(task_id)
            )
            return result
        finally:
            loop.close()

    except Exception as e:
        logger.error("同步前验证失败", task_id=task_id, error=str(e))
        return {
            "task_id": task_id,
            "status": "error",
            "error": str(e)
        }


@celery.task
def schedule_verification_after_sync(execution_id: int, delay_minutes: int = 5) -> Dict[str, Any]:
    """
    同步后延迟验证

    Args:
        execution_id: 执行记录ID
        delay_minutes: 延迟分钟数

    Returns:
        调度结果
    """
    try:
        from datetime import datetime, timedelta
        from celery import current_app

        # 计算执行时间
        eta = datetime.utcnow() + timedelta(minutes=delay_minutes)

        # 调度验证任务
        verify_sync_result.apply_async(
            args=[execution_id],
            eta=eta,
            queue="verification"
        )

        logger.info(
            "已调度同步后验证",
            execution_id=execution_id,
            delay_minutes=delay_minutes,
            eta=eta.isoformat()
        )

        return {
            "execution_id": execution_id,
            "status": "scheduled",
            "delay_minutes": delay_minutes,
            "eta": eta.isoformat()
        }

    except Exception as e:
        logger.error(
            "调度同步后验证失败",
            execution_id=execution_id,
            error=str(e)
        )
        return {
            "execution_id": execution_id,
            "status": "error",
            "error": str(e)
        }


@celery.task
def batch_verification(execution_ids: list) -> Dict[str, Any]:
    """
    批量验证

    Args:
        execution_ids: 执行记录ID列表

    Returns:
        批量验证结果
    """
    logger.info("开始批量验证", execution_count=len(execution_ids))

    try:
        results = []

        for execution_id in execution_ids:
            try:
                # 调用验证任务
                result = verify_sync_result.delay(execution_id)
                results.append({
                    "execution_id": execution_id,
                    "task_id": result.id,
                    "status": "queued"
                })
            except Exception as e:
                results.append({
                    "execution_id": execution_id,
                    "status": "error",
                    "error": str(e)
                })

        return {
            "status": "completed",
            "total_executions": len(execution_ids),
            "queued_count": len([r for r in results if r.get("status") == "queued"]),
            "error_count": len([r for r in results if r.get("status") == "error"]),
            "results": results
        }

    except Exception as e:
        logger.error("批量验证失败", error=str(e))
        return {
            "status": "error",
            "error": str(e),
            "total_executions": len(execution_ids)
        }


@celery.task
def cleanup_verification_cache() -> Dict[str, Any]:
    """
    清理验证缓存

    Returns:
        清理结果
    """
    try:
        logger.info("开始清理验证缓存")

        # TODO: 实现验证缓存清理逻辑
        # 例如：清理临时克隆的仓库目录

        logger.info("验证缓存清理完成")
        return {"status": "success", "message": "验证缓存清理完成"}

    except Exception as e:
        logger.error("验证缓存清理失败", error=str(e))
        return {"status": "failure", "error": str(e)}